package com.wuming.house.controller;

import com.wuming.house.core.BusinessException;
import com.wuming.house.core.CommonResult;
import com.wuming.house.core.JsonResult;
import com.wuming.house.model.Tag;
import com.wuming.house.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/web/tag")
public class TagController extends BaseController {

    @Autowired
    private TagService tagService;

    @RequestMapping("/toManageTag")
    public String toManageTag() {
        return "/tools/manageTag";
    }

    @RequestMapping("/toAddTag")
    public String toAddTag() {
        return "/tools/editTag";
    }

    @ResponseBody
    @RequestMapping(value = "/all", method = RequestMethod.POST)
    public JsonResult all() {
        try {
            List<Tag> tags = tagService.getAllTags();
            return new JsonResult<Object>(tags, "success", true);
        } catch (BusinessException be) {
            logger.error("发生业务异常{}", be.getMessage());
            return new JsonResult<Object>(null, "error", false);
        } catch (Exception e) {
            logger.error("发生系统异常{}", e.getMessage());
            return new JsonResult<Object>(null, "error", false);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult list(@RequestParam(defaultValue = "0") int pageIndex, @RequestParam(defaultValue = "10") int pageSize) {
        try {
            List<Tag> tags = tagService.getTagsByPage(pageIndex, pageSize);
            int total = tagService.getTotal();
            return CommonResult.createSuccessResult(tags, total, "查询标签成功");
        } catch (Exception e) {
            logger.error("发生业务异常,异常信息:{}", e.getMessage());
        }
        return CommonResult.createFailureResult("查询标签失败");
    }


    @ResponseBody
    @RequestMapping(value = "/save")
    public JsonResult save(Tag tag) {
        if (null == tag.getId()) {
            tag.setCreateDatetime(new Date());
            tagService.saveTag(tag);
            return new JsonResult(tag, "添加标签成功");
        } else {
            tagService.modifyTag(tag);
            return new JsonResult(tag, "更新标签成功");
        }
    }


    @ResponseBody
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public JsonResult delete(@PathVariable Long id) {
        logger.info("准备删除id:{}的标签", id);
        try {
            tagService.removeTagById(id);
            return new JsonResult(null, "删除成功", true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发生业务异常,异常信息:{}", e.getMessage());
            return new JsonResult(null, "删除失败", false);
        }
    }
}
